package com.agger.harmonyosthemeseditor.intelligent;

import org.apache.tools.zip.*;

import java.io.*;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.Deflater;

public class ZipFileManager
{
    public static void zip(String src, String archive) throws IOException
    {
        FileOutputStream f = new FileOutputStream(archive);
        CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());
        ZipOutputStream zos = new ZipOutputStream(csum);
        zos.setEncoding("UTF8");
        BufferedOutputStream out = new BufferedOutputStream(zos);
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.BEST_SPEED);
        File srcFile = new File(src);
        if (!srcFile.exists() || (srcFile.isDirectory() && srcFile.list().length == 0))
        {
            throw new FileNotFoundException();
        }
        src = src.replaceAll("\\\\", "/");
        String prefixDir;
        if (srcFile.isFile())
        {
            prefixDir = src.substring(0, src.lastIndexOf("/") + 1);
        } else {
            prefixDir = (src.replaceAll("/$", "") + "/");
        }
        writeZipFile(zos, out, srcFile, prefixDir);
        out.close();
    }

    private static void writeZipFile(ZipOutputStream zos, BufferedOutputStream bo, File srcFile, String prefixDir) throws IOException
    {
        ZipEntry zipEntry;
        String filePath = srcFile.getAbsolutePath().replaceAll("\\\\", "/").replaceAll("//", "/");
        if (srcFile.isDirectory())
        {
            filePath = filePath.replaceAll("/$", "") + "/";
        }
        String entryName = filePath.replace(prefixDir, "").replaceAll("/$", "");
        if (srcFile.isDirectory())
        {
            if (!"".equals(entryName))
            {
                zipEntry = new ZipEntry(entryName + "/");
                zos.putNextEntry(zipEntry);
            }
            File[] srcFiles = srcFile.listFiles();
            for (File file : srcFiles)
                writeZipFile(zos, bo, file, prefixDir);
        } else
        {
            BufferedInputStream bi = new BufferedInputStream(new FileInputStream(srcFile));
            zipEntry = new ZipEntry(entryName);
            zos.putNextEntry(zipEntry);
            byte[] buffer = new byte[1024];
            int readCount = bi.read(buffer);
            while (readCount != -1)
            {
                bo.write(buffer, 0, readCount);
                readCount = bi.read(buffer);
            }
            bo.flush();
            bi.close();
        }
    }
}
